/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_zml.htm
 *
 * Zhiqim Zml is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.zml.statement;

import org.zhiqim.kernel.util.Strings;
import org.zhiqim.zml.Expression;
import org.zhiqim.zml.ExpressionParser;
import org.zhiqim.zml.Statement;
import org.zhiqim.zml.ZmlVariable;
import org.zhiqim.zml.Zmls;
import org.zhiqim.zml.exception.StatementException;

/**
 * 格式化语句，调用语句并对显示返回值作Zmls.format，格式为：#{obj.getName()}
 * @see _Call 调用不显示返回值
 * @see _Echo 调用显示返回值
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class _Format extends Statement
{
    private Expression _expression;
    
    @Override
    public boolean isNesting()
    {
        return false;
    }
    
    @Override
    public void parseStatement() throws StatementException
    {
        String s = Strings.trim(getStatement(), FORMAT_BEGIN, FORMAT_END);
        
        try
        {
            _expression = ExpressionParser.parseExpression(s);
        }
        catch(Exception e)
        {
            throw new StatementException(this, FORMAT + e.getMessage());
        }
    }
    
    @Override
    public String process(ZmlVariable variableMap) throws StatementException
    {
        Object value = null;
        
        try
        {
            value = _expression.build(variableMap);
        }
        catch(Exception e)
        {
            throw new StatementException(this, FORMAT + e.getMessage(), e);
        }
        
        //结果为null返回null表示无返回文本，不为null转化为字符串，并作ZML格式化
        return (value == null)?null:Zmls.format(String.valueOf(ZmlVariable.chkDynamicVar(value)));
    }
}
